#!/bin/bash
set -euo pipefail
# Configuring the timeserver for the platform is often handled
# by pre-baking a config into a particular image for a platform, but
# that doesn't work for us because we have a single update stream.  Hence
# this generator dynamically inspects the platform and reconfigures chrony.
#
# AWS: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html
# Azure: https://docs.microsoft.com/en-us/azure/virtual-machines/linux/time-sync
# GCP: https://cloud.google.com/compute/docs/instances/managing-instances#configure-ntp
#
# Originally spawned from discussion in https://github.com/openshift/installer/pull/3513

# Generators don't have logging right now
# https://github.com/systemd/systemd/issues/15638
exec 1>/dev/kmsg; exec 2>&1

self=$(basename $0)
confpath=/run/coreos-platform-chrony.conf

# Yeah this isn't a completely accurate kernel argument parser but
# we don't have one shared across shell services at the moment.
platform="$(grep -Eo ' ignition.platform.id=[a-z]+' /proc/cmdline | cut -f 2 -d =)"
case "${platform}" in
    azure|aws|gcp) ;;  # OK, this is a platform we know how to support
    *) exit 0 ;;
esac

# Exit early if we have already been run once
if [[ -f "${confpath}" ]]; then
    echo "$self: ${confpath} already exists; skipping"
    exit 0
fi

# Exit early if chrony configuration as been changed from the image default
if ! cmp {/usr,}/etc/chrony.conf >/dev/null; then
    echo "$self: /etc/chrony.conf is modified; not changing the default"
    exit 0
fi

# If not set already (by host customization or this script), set
# PEERNTP=no so that DHCP-provided NTP servers are not added to chrony.
# By doing this we assume the better NTP server choice is the
# platform-provided link-local NTP server rather than others from DHCP.
# TODO: once https://bugzilla.redhat.com/show_bug.cgi?id=1828434 is
# resolved, this won't be required.
if [ ! -e /etc/sysconfig/network ] || ! grep -q "PEERNTP" /etc/sysconfig/network; then
    cat <<EOF >> /etc/sysconfig/network
# PEERNTP=no is automatically added by default when a platform-provided time
# source is available, but this behavior may be overridden through an Ignition
# config specifying PEERNTP=yes. See https://github.com/coreos/fedora-coreos-config/pull/412.
PEERNTP=no
EOF
fi

(echo "# Generated by $self - do not edit directly"
 sed -e s,'^makestep,#makestep,' -e s,'^pool,#pool,' -e s,'^leapsectz,#leapsectz,' < /etc/chrony.conf
cat <<EOF

# Allow the system clock step on any clock update.
# It will avoid the time resynchronization issue when VMs are resumed from suspend.
# See https://bugzilla.redhat.com/show_bug.cgi?id=1780165 for more information.
makestep 1.0 -1

EOF
) > "${confpath}"
case "${platform}" in
    azure)
        (echo '# See also https://docs.microsoft.com/en-us/azure/virtual-machines/linux/time-sync'
         echo 'refclock PHC /dev/ptp0 poll 3 dpoll -2 offset 0'
         echo 'leapsectz right/UTC'
        ) >> "${confpath}" ;;
    aws)
        (echo '# See also https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-time.html'
         echo 'server 169.254.169.123 prefer iburst minpoll 4 maxpoll 4'
        ) >> "${confpath}" ;;
    gcp)
        (echo '# See also https://cloud.google.com/compute/docs/instances/managing-instances#configure-ntp'
         echo '# and https://cloud.google.com/compute/docs/images/configuring-imported-images'
         echo 'server metadata.google.internal prefer iburst'
        ) >> "${confpath}" ;;
    *) echo "should not be reached" 1>&2; exit 1 ;;
esac
# Policy doesn't allow chronyd to read run_t
chcon --reference=/etc/chrony.conf "${confpath}"

UNIT_DIR="${1:-/tmp}"

unitconfpath="${UNIT_DIR}/chronyd.service.d/coreos-platform-chrony.conf"
mkdir -p $(dirname "${unitconfpath}")
cat >"${unitconfpath}" << EOF
[Service]
ExecStart=
ExecStart=/usr/sbin/chronyd -f ${confpath} \$OPTIONS
EOF

echo "$self: Updated chrony to use ${platform} configuration ${confpath}"
